package ias.deepsearch.com.helper.ui.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.yancloud.android.contractclient.databaseHelper.DatabaseDao;
import com.yancloud.android.contractclient.databaseHelper.DoiCallable;
import com.yancloud.android.contractclient.doip.HandleService;
import com.yancloud.android.contractclient.databaseHelper.PhoneInfoUtil;
import com.yancloud.android.manager.IAPIBinder;
import com.yancloud.android.manager.IAppConnector;
import com.yancloud.android.manager.PackageVersionPair;


import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import ias.deepsearch.com.helper.service.DaemonService;
import ias.deepsearch.com.helper.R;
import ias.deepsearch.com.helper.ui.fragment.AppEnableFragment;
import ias.deepsearch.com.helper.ui.fragment.DoiFragment;
import ias.deepsearch.com.helper.ui.fragment.InfoFragment;
import rx.functions.Action1;

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

   private DatabaseDao databaseDao;

    public IAppConnector conn;
    RxPermissions rxPermissions;
    private InfoFragment infoFragment;
    private SharedPreferences preferences;
    private HandleService handleService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        rxPermissions = new RxPermissions(this);
        //为了简单处理，我们在应用启动的时候检查权限，如果没有授权就直接退出
        checkPermissions();

        Intent intent = new Intent(this, DaemonService.class);
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        startService(intent);
        infoFragment = new InfoFragment();
        jumpToFragment(infoFragment);
        initDoi();
        //
        //




    }
    public void initDoi(){
        SharedPreferences sharedPreferences = getSharedPreferences("firstrun", 0);
        Boolean firstrun = sharedPreferences.getBoolean("first", true);
        if (firstrun) {//第一次则获取IMEI信息
            Map phoneInfoMap = PhoneInfoUtil.getPhoneInfo(HomeActivity.this);
            String imei = PhoneInfoUtil.getDeviceImei(HomeActivity.this);
            String brand = PhoneInfoUtil.getPhoneBrand();
            String model = PhoneInfoUtil.getPhoneModel();
            Log.d("手机IMEI",imei);
            Log.d("手机品牌",brand);
            Log.d("手机型号",model);
//            HandleService.RegisterPhone(imei,null);
            insertDo();
            Log.d("first",String.valueOf(firstrun));
            sharedPreferences.edit().putBoolean("first",false).commit();
        } else {
            insertDo();
        }

    }
    //获取DO信息并插入
    public void insertDo(){
        ServiceConnection serverConnector;
        databaseDao = DatabaseDao.getInstance(HomeActivity.this);
        serverConnector = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                HomeActivity.this.conn = IAppConnector.Stub.asInterface(service);
                ExecutorService threadPool = Executors.newSingleThreadExecutor();
                Set<String> pkgNameSet = new HashSet<>();
                try {
                    List<PackageVersionPair> list = conn.listPackages();
                    Log.d("包大小", String.valueOf(list.size()));
                    int i = 0;
                    for (PackageVersionPair pair : list) {

                        int index = pair.pkgName.indexOf(":");
                      //  Log.d("111",pair.pkgName+"111111111111111111111111111111");
                        String pkgName;
                        if(index != -1){
                             pkgName  = pair.pkgName.substring(0,pair.pkgName.indexOf(":"));
                        }else {
                            pkgName = pair.pkgName;
                        }
                        if(pkgNameSet.contains(pkgName)){
                            continue;
                        }else {
                            pkgNameSet.add(pkgName);
                            Log.d("包名",pkgName);
                        }
                        Log.d("pkgNameSetSize",String.valueOf(pkgNameSet.size()));
                        IBinder iBinder = conn.request(pair.pkgName, "1");
                        IAPIBinder app = IAPIBinder.Stub.asInterface(iBinder);
                        List<String> methods = app.getMethodNames();
                        JSONArray apiJsonArray = (JSONArray) JSONArray.parse(app.callMethod("getMethodDescriptions","CommPoter"));
                        for(int j = 0; j < apiJsonArray.size(); j++){
                            JSONObject apiJsonObj = apiJsonArray.getJSONObject(j);
                            String methodName = apiJsonObj.getString("mName");
                            String methodDes = apiJsonObj.getString("desp");
                            if (databaseDao.isExist(pkgName, methodName) == 0) {
                                Log.d("方法", methodName);
                                threadPool.submit(DoiCallable.of(pkgName,methodName,methodDes));
                                // String doi = HandleService.RegisterAPI(pair.pkgName, method, null);
                               // databaseDao.insertDoi(future.get(), pkgName, methodName, 0,1,null);
                            }
                        }

                       /* for (String method : methods) {
                            String[] methodName = method.split("\"");

                            if (databaseDao.isExist(pair.pkgName, methodName[1]) == 0) {
                                Log.d("方法", method);
                                Future<String> future = threadPool.submit(DoiCallable.of(pair.pkgName,method));
                               // String doi = HandleService.RegisterAPI(pair.pkgName, method, null);
                                databaseDao.insertDoi(future.get(), pair.pkgName, methodName[1], 0,0,null);
                            }
                            i++;
                        }*/
                        /*TestInsert
                        * */
                    }


                }catch (Exception e){
                    e.printStackTrace();
                }
                // Log.d("YanCloudClient", "connect!");
            }
            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        };
        Intent mIntent = new Intent();
        mIntent.setAction("com.yancloud.android.manager.ConnectService");
        mIntent.setPackage("ias.deepsearch.com.helper");
        HomeActivity.this.bindService(mIntent, serverConnector, Context.BIND_AUTO_CREATE);

    }


    void init(){
        
    }

    void checkPermissions(){
        rxPermissions
                .request(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if(aBoolean){
                            Toast.makeText(HomeActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                            init();

                        }else{
                            Toast.makeText(HomeActivity.this, "权限授权失败，退出", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                });

    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        //KLog.v("liuyi", "onWindowFocusChange---: " + hasFocus);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        switch (id){
            case R.id.nav_home:
                jumpToFragment(new InfoFragment());
                break;
            case R.id.nav_settings:
                jumpToFragment(new AppEnableFragment());
                break;
            case R.id.doi_list:
                jumpToFragment(new DoiFragment());
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }



    public void jumpToFragment(Fragment fragment){

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment now = fragmentManager.findFragmentById(R.id.fragment_container);
        if(now == null) {
            fragmentTransaction.add(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }else{
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        infoFragment.reflush();
    }
    @Override
    protected void onStop() {
        super.onStop();
    }

    //按返回键的时候应该销毁该页面
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode == KeyEvent.KEYCODE_BACK){
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
